<template>
  <div class="admin-info-container">
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>管理员信息</span>
        </div>
      </template>
      
      <div class="avatar-container">
        <div class="avatar-wrapper" @click="showCropper = true">
          <img 
            :src="currentAvatarUrl" 
            class="avatar" 
            alt="管理员头像"
          />
          <div class="avatar-hover-mask">
            <el-icon><Camera /></el-icon>
          </div>
        </div>
        <div class="avatar-text">点击更换头像</div>
        <el-button 
          type="primary" 
          size="small" 
          @click="handleUpdateAvatar"
          :disabled="!hasAvatarChanged"
          style="margin-top: 10px;"
        >
          更新头像
        </el-button>
      </div>

      <el-dialog
        v-model="showCropper"
        title="裁剪头像"
        width="600px"
        :close-on-click-modal="false"
      >
        <div class="cropper-container">
          <vue-cropper
            ref="cropperRef"
            :img="cropperImage"
            :autoCrop="true"
            :fixedBox="true"
            :centerBox="true"
            :fixed="true"
            :fixedNumber="[1, 1]"
            :info="true"
            :outputSize="1"
            outputType="png"
            @realTime="cropImage"
          />
        </div>
        <template #footer>
          <div class="cropper-buttons">
            <el-upload
              class="upload-trigger"
              :show-file-list="false"
              :auto-upload="false"
              accept="image/*"
              @change="handleImageSelected"
            >
              <el-button>选择图片</el-button>
            </el-upload>
            <el-button type="primary" @click="confirmCrop">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <el-form :model="adminForm" :rules="adminRules" ref="adminFormRef" label-width="100px">
        <el-form-item label="登录名称">
          <el-input :model-value="adminStore.adminInfo?.username" disabled />
        </el-form-item>
        <el-form-item label="管理员昵称" prop="nickname">
          <el-input v-model="adminForm.nickname" />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleUpdateNickname"
            :disabled="!hasNicknameChanged"
          >
            提交修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { useAdminStore } from '@/stores/admin'
import { VueCropper } from 'vue-cropper'
import 'vue-cropper/dist/index.css'
import { updateAdmin } from '@/api/admin'
import { useRouter } from 'vue-router'

const adminStore = useAdminStore()
const adminFormRef = ref(null)
const avatarUrl = ref('')
const originalAvatarUrl = ref('')
const showCropper = ref(false)
const cropperImage = ref('')
const cropperRef = ref(null)
const croppedImage = ref('')
const router = useRouter()

const adminForm = reactive({
  nickname: adminStore.adminInfo?.nickname || ''
})

// 检查昵称是否发生变化
const hasNicknameChanged = computed(() => {
  return adminForm.nickname !== adminStore.adminInfo?.nickname
})

const adminRules = {
  nickname: [
    { required: true, message: '请输入管理员昵称', trigger: 'blur' },
    { min: 2, max: 6, message: '昵称长度在2到6个字符之间', trigger: 'blur' }
  ]
}

// 检查头像是否发生变化
const hasAvatarChanged = computed(() => {
  return avatarUrl.value !== originalAvatarUrl.value && avatarUrl.value !== ''
})

// 图片选择处理函数
const handleImageSelected = async (uploadFile) => {
  const file = uploadFile.raw
  if (file) {
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件')
      return
    }
    try {
      const reader = new FileReader()
      await new Promise((resolve, reject) => {
        reader.onload = (e) => {
          cropperImage.value = e.target.result
          resolve()
        }
        reader.onerror = (e) => {
          reject(new Error('图片读取失败'))
        }
        reader.readAsDataURL(file)
      })
    } finally {
    }
  }
}

// 确认裁剪函数
const confirmCrop = async () => {
  if (cropperRef.value && cropperRef.value.getCropData) {
    try {
      await new Promise((resolve) => {
        cropperRef.value.getCropData((data) => {
          avatarUrl.value = data
          showCropper.value = false
          ElMessage.success('头像已选择，点击更新按钮保存更改')
          resolve()
        })
      })
    }  finally {
    }
  } else {
    ElMessage.error('请先选择图片')
  }
}

// 实时裁剪函数
const cropImage = async (data) => {
  try {
    if (data && data.url) {
      croppedImage.value = data.url
    }
  } finally {
  }
}

// 更新头像处理函数
const handleUpdateAvatar = async () => {
  try {
    if (!avatarUrl.value) {
      return ElMessage.warning('请先选择头像')
    }

    const compressedAvatar = await compressImage(avatarUrl.value)
    
    const response = await updateAdmin(adminStore.adminInfo.id, {
      avatar_type: 'custom',
      avatar_data: compressedAvatar
    })

    if (response.code === 200) {
      ElMessage.success('头像更新成功')
      adminStore.setAdminInfo({
        ...adminStore.adminInfo,
        avatar_type: 'custom',
        avatar_data: compressedAvatar
      })
      avatarUrl.value = compressedAvatar
      originalAvatarUrl.value = compressedAvatar
    }
  } catch (error) {
    ElMessage.error('头像更新失败')
  }
}

// 更新昵称的处理函数
const handleUpdateNickname = async () => {
  try {
    await adminFormRef.value.validate()
    
    const response = await updateAdmin(adminStore.adminInfo.id, {
      nickname: adminForm.nickname
    })

    if (response.code === 200) {
      ElMessage.success('昵称更新成功')
      adminStore.setAdminInfo({
        ...adminStore.adminInfo,
        nickname: adminForm.nickname
      })
    }
  } catch (error) {
    ElMessage.error('昵称更新失败')
  }
}

// 图片压缩函数
const compressImage = async (base64) => {
  try {
    return await new Promise((resolve) => {
      const img = new Image()
      img.src = base64
      img.onload = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        
        const maxSize = 200
        let width = img.width
        let height = img.height
        
        if (width > height) {
          if (width > maxSize) {
            height *= maxSize / width
            width = maxSize
          }
        } else {
          if (height > maxSize) {
            width *= maxSize / height
            height = maxSize
          }
        }
        
        canvas.width = width
        canvas.height = height
        
        ctx.drawImage(img, 0, 0, width, height)
        
        resolve(canvas.toDataURL('image/jpeg', 0.7))
      }
    })
  } finally {
  }
}

// 计算当前头像 URL
const currentAvatarUrl = computed(() => {
  if (avatarUrl.value) {
    return avatarUrl.value
  }
  return adminStore.adminInfo?.avatar_data || ''
})

// 初始化
onMounted(() => {
  if (adminStore.adminInfo?.avatar_data) {
    avatarUrl.value = adminStore.adminInfo.avatar_data
    originalAvatarUrl.value = adminStore.adminInfo.avatar_data
  }
})

// 如果有任何路由跳转相关代码
const handleSomeAction = () => {
  router.push('/admin/admin-profile')
}
</script>

<style scoped>
.admin-info-container {
  padding: 20px;
}

.info-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-wrapper {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  border: 2px solid #e0e0e0;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-hover-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-hover-mask .el-icon {
  font-size: 24px;
  color: white;
}

.avatar-wrapper:hover .avatar-hover-mask {
  opacity: 1;
}

.avatar-text {
  color: #606266;
  font-size: 14px;
  margin-top: 8px;
}

.cropper-container {
  height: 400px;
  width: 100%;
  overflow: hidden;
}

.cropper-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 10px 0;
}

:deep(.upload-trigger .el-upload) {
  display: block;
}

:deep(.vue-cropper) {
  height: 100%;
  width: 100%;
}

:deep(.cropper-box) {
  height: 100% !important;
}

:deep(.cropper-drag-box) {
  background-color: rgba(0, 0, 0, 0.6);
}

:deep(.cropper-modal) {
  background: rgba(0, 0, 0, 0.6);
}
</style> 